<?php

class Search extends Controller{

	public $useDB = array("Category", "Product");
	
	public function products($page=1) {
		$page = $page>0 ? $page : 1;
		$this->set("page", $page);
		
		removeEmptyItems($this->request->data["search"]);
		$search_params = $this->request->data["search"];
		if(!isset($search_params)) {
			$search_params = $this->request->named;
		}
		$this->set("search_params", $search_params);
		
		$products = array();
		if(!empty($search_params)) {
			$conditions = $this->dbProduct->buildConditionsFromSearch($search_params);
			$from = "products p LEFT JOIN product_categories pc ON p.id=pc.product_id";
			if($conditions !== false) {
				$this->set("total", $this->dbProduct->count(array(
					"conditions" => $conditions,
					"from" => $from
				)));
				$products = $this->dbProduct->findWithImage(array(
					"conditions" => $conditions,
					"offset" => array($page, PRODUCTS_PER_PAGE)
				));
			}
		}
		$this->set("products", $products);
		
	}
	
	public function keyword($keyword, $page=1){
		$keyword = trim($keyword);
		$this->set("keyword", $keyword);
		
		if(strlen($keyword)>0){
			$page = $page>0 ? $page : 1;
			$this->set("page", $page);
			$this->set("total", $this->dbProduct->count(array(
				"conditions" => array(
					"OR" => array(
						"products.name LIKE" => "'%$keyword%'",
					)
				)
			)));
			$this->set("products", $this->dbProduct->findWithImage(array(
				"conditions" => array(
					"OR" => array(
						"p.name LIKE" => "'%$keyword%'",
					)
				),
				"offset" => array($page, PRODUCTS_PER_PAGE)
			)));
		}
	}

}